package com.wzh.glsc.oss.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.oss.controller
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/index")
    public String index(HttpSession session){
        if(session.getAttribute("token")==null){
            return "login";
        }
        return "index";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String name,
                          String password
                            , String url
                            , HttpSession session
                        , HttpServletResponse response){
        session.setAttribute("name", name);
        session.setAttribute("password", password);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(uuid, name);
        Cookie oss_token = new Cookie("oss_token", uuid);
        response.addCookie(oss_token);
        if(!StringUtils.isEmpty(url)){
            return "redirect:"+url+"?token="+uuid;
        }else{
            return "index";
        }
    }

    @RequestMapping("/login")
    public String login(String url, HttpSession session, Model model
                        , @CookieValue(value = "oss_token",required = false) String ossToken){
        if(!StringUtils.isEmpty(ossToken)){
            return "redirect:"+url+"?token="+ossToken;
        }
        if(!StringUtils.isEmpty(url)){
            model.addAttribute("url",url);
        }
        if(session.getAttribute("name")==null){
            return "login";
        }else {
            return "index";
        }
    }

}
